import { useState } from 'react';
import { ChatOpenAI } from "@langchain/openai";

export default function HomePage() {
  const [messages, setMessages] = useState<Array<{role: string, content: string}>>([]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const chatModel = new ChatOpenAI({
        modelName: "gpt-3.5-turbo",
        streaming: true,
        configuration: {
          apiKey: 'xxx', // Replace with your OpenAI API key
          baseURL: 'https://xxx' // Replace with your OpenAI API endpoint 代理地址
        },
      });

      const newMessages = [...messages, {role: 'user', content: input}];
      setMessages(newMessages);
      setInput('');
      
      let fullResponse = '';
      const response = await chatModel.stream(newMessages.map(m => m.content).join('\n'));
      
      for await (const chunk of response) {
        fullResponse += chunk.content;
        setMessages([...newMessages, {role: 'assistant', content: fullResponse}]);
      }
      
      setLoading(false);
    } catch (error) {
      console.error(error);
      setLoading(false);
    }
  };

  return (
    <div style={{ maxWidth: '800px', margin: '0 auto', padding: '20px', fontFamily: 'Arial, sans-serif' }}>
      <h2 style={{ color: '#333', textAlign: 'center' }}>来唠唠</h2>
      <div style={{
        height: '400px',
        overflow: 'auto',
        border: '1px solid #e0e0e0',
        borderRadius: '8px',
        padding: '15px',
        backgroundColor: '#f9f9f9',
        boxShadow: 'inset 0 1px 3px rgba(0,0,0,0.1)'
      }}>
        {messages.map((msg, i) => (
          <div 
            key={i} 
            style={{
              margin: '10px 0',
              display: 'flex',
              flexDirection: msg.role === 'user' ? 'row-reverse' : 'row',
            }}
          >
            <div 
              style={{
                maxWidth: '70%',
                padding: '10px 15px',
                borderRadius: '18px',
                backgroundColor: msg.role === 'user' ? '#dcf8c6' : '#ffffff',
                border: '1px solid #e0e0e0',
                boxShadow: '0 1px 2px rgba(0,0,0,0.1)'
              }}
            >
              <strong style={{ color: msg.role === 'user' ? '#075e54' : '#333' }}>
                {msg.role === 'user' ? '我' : 'AI'}:
              </strong> 
              <div style={{ wordBreak: 'break-word' }}>{msg.content}</div>
            </div>
          </div>
        ))}
      </div>
      <form onSubmit={handleSubmit} style={{ marginTop: '20px', display: 'flex' }}>
        <input 
          type="text" 
          value={input} 
          onChange={(e) => setInput(e.target.value)} 
          disabled={loading}
          style={{
            flex: 1,
            padding: '12px',
            borderRadius: '24px',
            border: '1px solid #e0e0e0',
            outline: 'none',
            fontSize: '16px',
            boxShadow: '0 1px 2px rgba(0,0,0,0.1)'
          }}
          placeholder="请输入"
        />
        <button 
          type="submit" 
          disabled={loading} 
          style={{
            padding: '12px 24px',
            marginLeft: '10px',
            borderRadius: '24px',
            backgroundColor: '#075e54',
            color: 'white',
            border: 'none',
            cursor: 'pointer',
            fontSize: '16px',
            transition: 'background-color 0.3s'
          }}
          onMouseEnter={(e) => {
            if (!loading) {
              (e.target as HTMLButtonElement).style.backgroundColor = '#054a42';
            }
          }}
          onMouseLeave={(e) => {
            if (!loading) {
              (e.target as HTMLButtonElement).style.backgroundColor = '#075e54';
            }
          }}
        >
          {loading ? 'Sending...' : 'Send'}
        </button>
      </form>
    </div>
  );
}
